//
//  MNDCalendarViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/7/31.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDCalendarViewController.h"
#import "FSCalendar.h"
#import "NSDate+JKExtension.h"
#import "NSDate+JKExtension.h"
#import "NSDate+JKUtilities.h"
#import "UIImage+JKColor.h"
#import "UIButton+JKImagePosition.h"
#import "MNDCalendarCell.h"
#import "HooDatePicker.h"

@interface MNDCalendarViewController () <FSCalendarDataSource, FSCalendarDelegate, FSCalendarDelegateAppearance, UITableViewDataSource, UITableViewDelegate, HooDatePickerDelegate>

@property (weak, nonatomic) IBOutlet FSCalendar *calendarView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *returnMonthLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalReturnLabel;

@property (strong, nonatomic) UIButton *rightButton;

@property(nonatomic, strong) NSMutableDictionary *calendarDates;
@property(nonatomic, strong) NSMutableArray *datesWithEvents;
@property(nonatomic, strong) NSMutableArray *returnList;

@property (strong, nonatomic) NSDate *selectedDate;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarHeight;

@property(nonatomic, weak) HooDatePicker *datePicker;


@end

@implementation MNDCalendarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.leftBarTintColor = [UIColor whiteColor];
    self.barTitleColor = [UIColor whiteColor];
    self.naviBarTranslucent = YES;
    
    self.calendarDates = [NSMutableDictionary dictionary];
    self.datesWithEvents = [NSMutableArray array];
    self.returnList = [NSMutableArray array];
    
    self.calendarView.headerHeight = 64;
    self.calendarView.weekdayHeight = 45.0;
    
    self.tableView.tableFooterView = [UIView new];

    [self initialLeftBarButtons];
    [self initialRightBarButtons];
    
    NSString *currentDate = [[NSDate date] jk_stringWithFormat:@"yyyy-MM-dd"];
    self.selectedDate = [NSDate jk_dateWithString:currentDate format:@"yyyy-MM-dd"];
    [self loadDataWithDate:currentDate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)loadDataWithDate:(NSString *)date {
    
    self.selectedDate = [NSDate jk_dateWithString:date format:@"yyyy-MM-dd"];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"y": @(self.selectedDate.jk_year), @"m": @(self.selectedDate.jk_month)}];
    
    __weak __typeof(self)weakSelf = self;
    [APIManager sendRequestWithPath:API_RETURN_CALENDAR parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [weakSelf configCalendarDates:responseModel.data withDate:date];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configCalendarDates:(NSDictionary *)dict withDate:(NSString *)date {
    
    self.calendarDates = [dict[@"calendar_list"] mutableCopy];
    
    //回款总额
    NSDate *currentDate = [NSDate jk_dateWithString:date format:@"yyyy-MM-dd"];
    self.returnMonthLabel.text = [NSString stringWithFormat:@"%zd月回款总额(元)", currentDate.jk_month];
    NSNumber *returnTotal = dict[@"repayment_total"];
    self.totalReturnLabel.text = returnTotal.doubleValue <= 0? @"0.00": [NSString stringWithFormat:@"%.02f", returnTotal.doubleValue];
    
    [self.datesWithEvents removeAllObjects];
    [self.returnList removeAllObjects];
    
    //日历配置
    NSArray *dates = [self.calendarDates.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];  //按日期大小排序
    }];
    for (NSString *dateStr in dates) {
        
        NSDictionary *dateDict = self.calendarDates[dateStr];
        NSNumber *repayment = dateDict[@"repayment"];
        if (repayment.doubleValue > 0) {
            [self.datesWithEvents addObject: dateStr];
            NSDictionary *returnDict = @{@"date": dateStr, @"repayment": repayment};
            [self.returnList addObject:returnDict];
        }
    }
    
    [self.calendarView reloadData];
    [self.tableView reloadData];
}

- (void)rightBarButtonAction:(id)sender {
    
    if (self.datePicker) {
        return;
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *maxDate = [formatter dateFromString:@"2050-01-01"];
    NSDate *minDate = [formatter dateFromString:@"2013-02-01"];
    
    HooDatePicker *picker = [[HooDatePicker alloc] initDatePickerMode:HooDatePickerModeYearAndMonth
                                                              minDate:minDate
                                                           maxMamDate:maxDate
                                                    andAddToSuperView:KeyWindow];
    picker.hideSelectedLine = YES;
    picker.delegate = self;
    
    [picker show];
    
    self.datePicker = picker;
}

- (void)datePicker:(HooDatePicker *)datePicker dateDidChange:(NSDate *)date {
    NSLog(@"date: %@", date);
}

- (void)datePicker:(HooDatePicker *)dataPicker didSelectedDate:(NSDate *)date {
    [self removeDatePicker];
    //所选日期与当前显示日期相同，不做请求处理
    if ([self.selectedDate jk_isSameYearAsDate:date] && [self.selectedDate jk_isSameMonthAsDate:date]) {
        return;
    }
    self.selectedDate = date;
    NSString *changeDate = [NSDate jk_stringWithDate:date format:@"yyyy年MM月"];
    [self.rightButton setTitle:changeDate forState:UIControlStateNormal];
    [self.rightButton sizeToFit];
    self.calendarView.currentPage = date;
    [self.calendarView reloadData];
    
    NSString *selectDate = [date jk_stringWithFormat:@"yyyy-MM-dd"];
    [self loadDataWithDate:selectDate];

}

- (void)datePicker:(HooDatePicker *)datePicker didCancel:(UIButton *)sender {
    
    [self removeDatePicker];
}

- (void)removeDatePicker {
    [self.datePicker removeFromSuperview];
    self.datePicker = nil;
}

#pragma mark - FSCalendarDataSource

- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar {
    return [NSDate jk_dateWithString:@"2013-01-01" format:@"yyyy-MM-dd"];
}

- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date {
    NSString *dateStr = [NSDate jk_stringWithDate:date format:@"yyyyMMdd"];
    if ([self.datesWithEvents containsObject:dateStr]) {
        
        return 1;
    }
    return 0;
}

#pragma mark - FSCalendarDelegateAppearance

- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance borderDefaultColorForDate:(NSDate *)date {
    
//    if ([date jk_isToday]) {
//        return [UIColor whiteColor];
//    }
    
    return nil;
}

#pragma mark - FSCalendarDelegate

- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated {
    
    [UIView animateWithDuration:0.25 animations:^{
        self.calendarHeight.constant = bounds.size.height;
    }];
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar {
    NSString *changeDate = [NSDate jk_stringWithDate:calendar.currentPage format:@"yyyy年MM月"];
    [self.rightButton setTitle:changeDate forState:UIControlStateNormal];
    [self.rightButton sizeToFit];

    NSString *date = [NSDate jk_stringWithDate:calendar.currentPage format:@"yyyy-MM-dd"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadDataWithDate:date];
    });
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    NSString *selectedDate = [NSDate jk_stringWithDate:date format:@"yyyy-MM-dd"];
    NSLog(@"selected date: %@", selectedDate);
}

#pragma mark - UITableView Datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.returnList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * const cellIdentifier = @"cell";
    MNDCalendarCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    NSDictionary *dict = self.returnList[indexPath.row];
    NSDate *date = [NSDate jk_dateWithString:dict[@"date"] format:@"yyyyMMdd"];
    cell.returnDateLabel.text = [NSString stringWithFormat:@"%02zd月%02zd日", date.jk_month, date.jk_day];
    NSNumber *returnMoney = dict[@"repayment"];
    cell.returnMoneyLabel.text = [NSString stringWithFormat:@"%.02f", returnMoney.doubleValue];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 初始化左右按钮

- (void)initialLeftBarButtons {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:[UIColor whiteColor]];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)initialRightBarButtons {
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.rightButton setImage:[UIImage imageNamed:@"return_list_black_dropdown"] forState:UIControlStateNormal];
    
    NSDate *date = [NSDate date];
    NSString *today = [date jk_stringWithFormat:@"yyyy年MM月"];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [self.rightButton setTitle:today forState:UIControlStateNormal];
    [self.rightButton sizeToFit];
    self.rightButton.tintColor = [UIColor whiteColor];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.rightButton jk_setImagePosition:LXMImagePositionRight spacing:8];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.navigationItem.rightBarButtonItem = item;
    
    [self.rightButton addTarget:self action:@selector(rightBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
